package com.bookrecomm.service.impl;

import com.bookrecomm.dao.BookRepository;
import com.bookrecomm.dao.FavoriteRepository;
import com.bookrecomm.dao.UserRepository;
import com.bookrecomm.entity.Book;
import com.bookrecomm.entity.Favorite;
import com.bookrecomm.entity.User;
import com.bookrecomm.service.BookService;
import com.bookrecomm.service.FavoriteService;
import com.bookrecomm.vo.BookVO;
import com.bookrecomm.vo.PageVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 收藏服务实现类
 * 实现收藏相关的业务逻辑
 */
@Service
public class FavoriteServiceImpl implements FavoriteService {

    @Autowired
    private FavoriteRepository favoriteRepository;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private BookRepository bookRepository;

    @Autowired
    private BookService bookService;

    /**
     * 添加收藏
     * @param userId 用户ID
     * @param bookId 图书ID
     * @return 是否添加成功
     */
    @Override
    @Transactional
    public boolean addFavorite(Long userId, Long bookId) {
        // 如果userId为null，则获取当前登录用户ID
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            userId = user.getId();
        }

        // 检查用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 检查图书是否存在
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new RuntimeException("图书不存在"));

        // 检查是否已收藏
        if (favoriteRepository.existsByUser_IdAndBook_Id(userId, bookId)) {
            return true; // 已收藏，直接返回成功
        }

        // 创建收藏记录
        Favorite favorite = new Favorite();
        favorite.setUserId(userId);
        favorite.setBookId(bookId);
        favorite.setCreatedAt(LocalDateTime.now());

        // 保存收藏记录
        favoriteRepository.save(favorite);

        // 更新图书收藏数
        book.setFavoriteCount(book.getFavoriteCount() + 1);
        bookRepository.save(book);

        // 更新用户收藏数
        user.setFavoriteCount(user.getFavoriteCount() + 1);
        userRepository.save(user);

        return true;
    }

    /**
     * 取消收藏
     * @param userId 用户ID
     * @param bookId 图书ID
     * @return 是否取消成功
     */
    @Override
    @Transactional
    public boolean removeFavorite(Long userId, Long bookId) {
        // 如果userId为null，则获取当前登录用户ID
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            userId = user.getId();
        }

        // 检查用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 检查图书是否存在
        Book book = bookRepository.findById(bookId)
                .orElseThrow(() -> new RuntimeException("图书不存在"));

        // 检查是否已收藏
        Favorite favorite = favoriteRepository.findByUser_IdAndBook_Id(userId, bookId)
                .orElse(null);

        if (favorite == null) {
            return true; // 未收藏，直接返回成功
        }

        // 删除收藏记录
        favoriteRepository.delete(favorite);

        // 更新图书收藏数
        if (book.getFavoriteCount() > 0) {
            book.setFavoriteCount(book.getFavoriteCount() - 1);
            bookRepository.save(book);
        }

        // 更新用户收藏数
        if (user.getFavoriteCount() > 0) {
            user.setFavoriteCount(user.getFavoriteCount() - 1);
            userRepository.save(user);
        }

        return true;
    }

    /**
     * 检查是否已收藏
     * @param userId 用户ID
     * @param bookId 图书ID
     * @return 是否已收藏
     */
    @Override
    public boolean isFavorite(Long userId, Long bookId) {
        // 如果userId为null，则获取当前登录用户ID
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            if (authentication == null || !authentication.isAuthenticated()) {
                return false; // 未登录
            }
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElse(null);
            if (user == null) {
                return false; // 用户不存在
            }
            userId = user.getId();
        }

        return favoriteRepository.existsByUser_IdAndBook_Id(userId, bookId);
    }

    /**
     * 获取用户收藏的图书列表
     * @param userId 用户ID
     * @param pageable 分页参数
     * @return 分页图书列表
     */
    @Override
    public PageVO<BookVO> getUserFavorites(Long userId, Pageable pageable) {
        // 如果userId为null，则获取当前登录用户ID
        final Long finalUserId;
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            finalUserId = user.getId();
        } else {
            finalUserId = userId;
        }

        // 检查用户是否存在
        userRepository.findById(finalUserId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 查询用户收藏的图书ID列表
        Page<Favorite> favoritePage = favoriteRepository.findByUserId(finalUserId, pageable);
        List<Long> bookIds = favoritePage.getContent().stream()
                .map(Favorite::getBookId)
                .collect(Collectors.toList());

        // 查询图书详情
        List<Book> books = bookRepository.findAllById(bookIds);

        // 按照收藏顺序排序
        List<Book> sortedBooks = bookIds.stream()
                .map(id -> books.stream()
                        .filter(book -> book.getId().equals(id))
                        .findFirst()
                        .orElse(null))
                .filter(book -> book != null)
                .collect(Collectors.toList());

        // 转换为VO对象
        List<BookVO> bookVOs = sortedBooks.stream()
                .map(book -> bookService.convertToBookVO(book, finalUserId))
                .collect(Collectors.toList());

        // 创建分页VO对象
        PageVO<BookVO> pageVO = new PageVO<>();
        pageVO.setContent(bookVOs);
        pageVO.setTotalElements(favoritePage.getTotalElements());
        pageVO.setTotalPages(favoritePage.getTotalPages());
        pageVO.setSize(favoritePage.getSize());
        pageVO.setNumber(favoritePage.getNumber());

        return pageVO;
    }

    /**
     * 获取用户收藏数量
     * @param userId 用户ID
     * @return 收藏数量
     */
    @Override
    public Long countUserFavorites(Long userId) {
        // 如果userId为null，则获取当前登录用户ID
        if (userId == null) {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            String username = authentication.getName();
            User user = userRepository.findByUsername(username)
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            userId = user.getId();
        }

        return favoriteRepository.countByUserId(userId);
    }

    /**
     * 获取图书被收藏数量
     * @param bookId 图书ID
     * @return 被收藏数量
     */
    @Override
    public Long countBookFavorites(Long bookId) {
        return favoriteRepository.countByBookId(bookId);
    }
}
